<?php
namespace app\admin\controller;

use app\common\model\AdminLog;
use app\common\model\AdminUser as AdminUserModel;
use app\common\model\AuthGroup as AuthGroupModel;
use app\common\model\AuthGroupAccess as AuthGroupAccessModel;
use app\common\controller\AdminBase;
use app\common\model\AuthGroupAccess;
use think\Config;
use think\Db;
use think\Request;
use think\Session;

/**
 * 管理员管理
 * Class AdminUser
 * @package app\admin\controller
 */
class AdminUser extends AdminBase
{
    protected $admin_user_model;
    protected $auth_group_model;
    protected $auth_group_access_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->admin_user_model        = new AdminUserModel();
        $this->auth_group_model        = new AuthGroupModel();
        $this->auth_group_access_model = new AuthGroupAccessModel();
    }

    /**
     * 账户设置
     * @return mixed
     */
    public function account_index()
    {
        $admin_id  = Session::get('admin_id');
        $user_info = AdminUserModel::where('id', $admin_id)->find();

        return $this->fetch('system/change_password', ['user_info' => $user_info]);
    }


    /**
     * 更新密码
     */
    public function updatePassword()
    {
        if ($this->request->isPost()) {
            $admin_id    = Session::get('admin_id');
            $data   = $this->request->param();
            $result = Db::name('admin_user')->find($admin_id);

            if ($result['password'] == md5($data['old_password'] . Config::get('salt'))) {
                if ($data['password'] == $data['confirm_password']) {
                    $new_password = md5($data['password'] . Config::get('salt'));
                    $res          = Db::name('admin_user')->where(['id' => $admin_id])->setField('password', $new_password);

                    if ($res !== false) {
                        $action='密码'.$admin_id;
                        $this->getLog('3', $action);
                        $this->success('修改成功');
                    } else {
                        $this->error('修改失败');
                    }
                } else {
                    $this->error('两次密码输入不一致');
                }
            } else {
                $this->error('原密码不正确');
            }
        }
    }

    /**
     * 管理员管理
     * @return mixed
     */
    public function index(Request $request)
    {
        $limit   = $request->param('limit') ?: 15;
        $page    = $request->param('page') ?: 1;
        $keyword = $request->param('keyword');
        $group_id = $request->param('group_id');
        $where   = [];
        if ($keyword) {
            $where['car_admin_user.username|car_admin_user.real_name'] = ['like', "%{$keyword}%"];
        }
        if($group_id){
            $where['car_auth_group_access.group_id'] = $group_id;
        }

        $admin_user_list = AdminUserModel::where($where)
            ->join('car_auth_group_access', 'car_auth_group_access.uid = car_admin_user.id')
            ->paginate($limit, false, ['page' => $page, 'query' => ['keyword' => $keyword, 'group_id' => $group_id]]);

        foreach ($admin_user_list as $item=>$value){
            $group_acc_id = AuthGroupAccess::where('uid',$value['id'])->value('group_id');
            $admin_user_list[$item]['belong_dept'] = AuthGroupModel::where('id',$group_acc_id)->value('title');
            $admin_user_list[$item]['last_login_date'] = date('Y-m-d H:i:s',AdminLog::where('admin_user_id',$value['id'])->order(['id'=>'desc'])->value('create_time'));
        }

        $dept_list = AuthGroupModel::all();


        return $this->fetch('index', ['admin_user_list' => $admin_user_list,'dept_list'=>$dept_list,'keyword'=>$keyword,'group_id'=>$group_id]);
    }

    public function changeStatus(Request $request)
    {
        $status = $request->param('status');
        $id     = $request->param('id');
        if (AdminUserModel::where('id', $id)->update(['status' => $status])) {
            return json(['status' => 1, 'code' => 200]);
        }
        return json(['status' => 0, 'code' => 500]);
    }

    /**
     * 添加管理员
     * @return mixed
     */
    public function add()
    {
        $this->auth_group_access_model;
        $auth_group_list = $this->auth_group_model->select();
        return $this->fetch('add', ['auth_group_list' => $auth_group_list]);
    }

    /**
     * 保存管理员
     * @param $group_id
     */
    public function save(Request $request)
    {

        $data['username']         = $request->param('username');
        $data['real_name']        = $request->param('real_name');
        $data['email']            = $request->param('email');
        $data['remark']           = $request->param('remark')?:'';
        $data['mobile']           = $request->param('mobile');
        $data['group_id']         = $request->param('group_id');
        $data['password']         = $request->param('password');
        $data['confirm_password'] = $request->param('confirm_password');
        $data['status']           = $request->param('status');

        $validate_result = $this->validate($data, 'AdminUser');

        if ($validate_result !== true) {
            $this->error($validate_result);
        }
        $data['password'] = md5($data['password'] . Config::get('salt'));

        $auth_group_access['group_id'] = $data['group_id'];
        unset($data['group_id'],$data['confirm_password']);

        $res                      = AdminUserModel::create($data);
        $auth_group_access['uid'] = $res->id;
        if ($res && AuthGroupAccessModel::create($auth_group_access)) {
            $action = '管理员';
            $this->getLog("1", $action);
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }

    }

    /**
     * 编辑管理员
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $admin_user             = $this->admin_user_model->find($id);
        $auth_group_list        = $this->auth_group_model->select();
        $auth_group_access      = $this->auth_group_access_model->where('uid', $id)->find();
        $admin_user['group_id'] = $auth_group_access['group_id'];

        return $this->fetch('edit', ['admin_user' => $admin_user, 'auth_group_list' => $auth_group_list]);
    }

    /**
     * 更新管理员
     * @param $id
     * @param $group_id
     */
    public function update($id, $group_id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'AdminUser');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $admin_user = $this->admin_user_model->find($id);

                $admin_user->id       = $id;
                $admin_user->username = $data['username'];
                $admin_user->email   = $data['email'];
                $admin_user->real_name   = $data['real_name'];
                $admin_user->remark   = $data['remark'];
                $admin_user->mobile   = $data['mobile'];
                $admin_user->status   = $data['status'];

                if (!empty($data['password']) && !empty($data['confirm_password'])) {
                    $admin_user->password = md5($data['password'] . Config::get('salt'));
                }
                if ($admin_user->save() !== false) {
                    $auth_group_access['uid']      = $id;
                    $auth_group_access['group_id'] = $group_id;
                    $this->auth_group_access_model->where('uid', $id)->update($auth_group_access);
                    $action = '管理员ID'.$id;
                    $this->getLog("3",$action);
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除管理员
     * @param $id
     */
    public function delete($id)
    {
        if ($id == 1) {
            $this->error('默认管理员不可删除');
        }
        if ($this->admin_user_model->destroy($id)) {
            $action = "管理员ID:".$id;
            $this->getLog("2",$action);
            $this->auth_group_access_model->where('uid', $id)->delete();
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}